package cn.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import cn.pojo.Detail;
import cn.pojo.Sort;
import cn.service.DetailService;
import cn.service.SortService;
import cn.util.Page;

@Controller
@RequestMapping("/detail")
public class DetailController {
	@Resource
	private DetailService detailService;
	@Resource
	private SortService sortService;

	@RequestMapping("/detailList")
	// 分页查看商品明细
	public ModelAndView detailList(@RequestParam(value = "sortId", defaultValue = "0", required = false) Long sortId,
			@RequestParam(name = "pageNum", defaultValue = "1", required = false) Integer pageNum,
			HttpServletRequest request, HttpServletResponse response, ModelAndView md) {
		Page<Detail> page = new Page<Detail>();
		page.init(detailService.totalCount(sortId), pageNum);
		List<Detail> list = detailService.getAllDetails(sortId, page.getRowNum(), Page.pageCount);
		page.setList(list);
		if (list != null) {
			md.addObject("PAGE", page);
			md.addObject("SORTID", sortId);
			md.setViewName("detailList");
			return md;
		}
		return md;
	}

	// 根据id显示商品明细
	@RequestMapping("/toUpdateGoods")
	public ModelAndView toUpdateGoods(@RequestParam(name = "id") Integer id,
			@RequestParam(value = "sortId", defaultValue = "0", required = false) Long sortId, ModelAndView md) {
		Detail detail = detailService.getDetailById(id);
		Sort sort = sortService.getSortById(sortId);
		md.addObject("SORT", sort);
		md.addObject("DETAIL", detail);
		md.setViewName("updateGoods");
		return md;
	}

	@RequestMapping("/updateGoods")
	public String updateGoods(@RequestParam(value = "buyCount", defaultValue = "0", required = false) Integer buyCount,
			@RequestParam(value = "id", defaultValue = "0", required = false) Long id,
			@RequestParam(value = "remaining", defaultValue = "0", required = false) Integer remaining) {
		int s = remaining - buyCount;
		System.out.println(s + ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
		int i = detailService.updateDetail(s, id);
		return "redirect:/detail/detailList";
	}
}
